package com.lyncs.ods.modules.share.strategy;

import com.lyncs.ods.common.exception.ApiException;
import com.lyncs.ods.modules.company.model.CompanyInvitationLog;
import com.lyncs.ods.modules.company.service.CompanyInvitationLogService;
import com.lyncs.ods.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author alex
 * @date 2022/4/21 22:17
 * @description
 */
@Slf4j
public abstract class ShareStrategy {

    /**
     * 处理请求
     *
     * @param key key
     */
    public Object exec(String key) {
        CompanyInvitationLog invitationLog = SpringUtils.getBean(CompanyInvitationLogService.class).lambdaQuery()
                .eq(CompanyInvitationLog::getKey, key)
                //永不过期链接或者未过期链接
                .and(wrapper -> wrapper.isNull(CompanyInvitationLog::getExpireTime).or().le(CompanyInvitationLog::getExpireTime, LocalDateTime.now()))
                .orderByDesc(CompanyInvitationLog::getCreateTime)
                .last(" limit 1")
                .one();
        if (Objects.isNull(invitationLog) || StringUtils.isBlank(invitationLog.getData())) {
            throw new ApiException("invited url not found or expired");
        }
        log.info("start handler share message:key{},data:{}", key, invitationLog.getData());
        Object result = handle(invitationLog.getData());
        log.info("end handler share message,result:{}", result);
        return result;
    }

    /**
     * 处理逻辑
     *
     * @param data 数据，json格式
     */
    protected abstract Object handle(String data);
}
